package com.qyhl.webtv.module_microvideo.shortvideo.classic;


import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.flyco.tablayout.SlidingTabLayout;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.live.TeleTextBean;
import com.qyhl.webtv.commonlib.entity.microvideo.ClassicCateBean;
import com.qyhl.webtv.commonlib.entity.microvideo.ClassicHomeBean;
import com.qyhl.webtv.commonlib.entity.news.AdvertiseBean;
import com.qyhl.webtv.commonlib.utils.TranslucentScrollView;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.PersonalViewPager;
import com.qyhl.webtv.module_microvideo.R;
import com.qyhl.webtv.module_microvideo.R2;
import com.qyhl.webtv.module_microvideo.shortvideo.classic.news.ClassicHomeNewsFragment;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.stx.xhb.androidx.XBanner;
import com.stx.xhb.androidx.transformers.Transformer;
import com.weavey.loading.lib.LoadingLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


@Route(path = ARouterPathConstant.CLASSIC_HOME)
public class ClassicHomeActivity extends BaseActivity implements ClassicHomeContract.ClassicHomeView, TranslucentScrollView.OnScrollChangedListener {
    @BindView(R2.id.banner)
    XBanner banner;
    @BindView(R2.id.enter_one)
    ImageButton enterOne;
    @BindView(R2.id.enter_two)
    ImageButton enterTwo;
    @BindView(R2.id.enter_layout)
    LinearLayout enterLayout;
    @BindView(R2.id.adv_banner)
    XBanner advBanner;
    @BindView(R2.id.tabLayout)
    SlidingTabLayout tabLayout;
    @BindView(R2.id.viewPager)
    PersonalViewPager viewPager;
    @BindView(R2.id.pager_layout)
    LinearLayout pagerLayout;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.live_layout)
    RelativeLayout liveLayout;
    @BindView(R2.id.live_cover)
    RoundedImageView liveCover;
    @BindView(R2.id.live_tag)
    ImageView liveTag;
    @BindView(R2.id.title)
    ImageView titleLayout;
    @BindView(R2.id.live_title)
    TextView liveTitle;
    @BindView(R2.id.scroll_view)
    TranslucentScrollView scrollView;
    @BindView(R2.id.toolbar)
    Toolbar toolbar;
    @BindView(R2.id.toolbar_layout)
    RelativeLayout toolbarLayout;

    private ClassicHomePresenter mPresenter;

    private ClassicHomeBean mBean;

    private float headerHeight;//顶部高度
    private float minHeaderHeight;//顶部最低高度，即Bar的高度

    @Override
    protected int getContentView() {
        return R.layout.micro_activity_classic;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.statusBarDarkFont(false)
                .titleBar(toolbar)
                .init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);
        mPresenter = new ClassicHomePresenter(this);
        scrollView.setOnScrollChangedListener(this);

        setSupportActionBar(toolbar);
        initMeasure();

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(false);

        mPresenter.getHomeData();
    }

    private void initMeasure() {
        headerHeight = StringUtils.dip2px(this, 140);
        minHeaderHeight = StringUtils.dip2px(this, 68);
    }

    @Override
    protected void setListener() {
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getHomeData();
            }
        });

        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getHomeData();
            }
        });

        banner.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner banner, Object model, View view, int position) {
                ClassicCateBean bean = (ClassicCateBean) model;
                skip(bean, true);
            }
        });

        advBanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner banner, Object model, View view, int position) {
                AdvertiseBean bean = (AdvertiseBean) model;
                advSkip(bean);
            }
        });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(final int position) {
                // 切换到当前页面，重置高度
                viewPager.requestLayout();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void setHomeData(ClassicHomeBean bean) {
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setStatus(LoadingLayout.Success);
        refresh.finishRefresh();
        mBean = bean;
        if (bean.getTop() != null && bean.getTop().size() > 0) {
            banner.setVisibility(View.VISIBLE);

            banner.setPageTransformer(Transformer.Scale);
            banner.offsetTopAndBottom(10);
            banner.setData(R.layout.micro_layout_classic_home_banner, bean.getTop(), null);
            banner.loadImage(new XBanner.XBannerAdapter() {
                @Override
                public void loadBanner(XBanner banner, Object model, View view, int position) {
                    ImageView bannerCover = view.findViewById(R.id.banner_cover);
                    TextView title = view.findViewById(R.id.title);
                    title.setText(((ClassicCateBean) model).getName());
                    Glide.with(ClassicHomeActivity.this)
                            .load(((ClassicCateBean) model).getCover())
                            .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                            .into(bannerCover);
                }
            });

        } else {
            banner.setVisibility(View.GONE);
        }

        if (bean.getCate() != null && bean.getCate().size() > 0) {
            enterLayout.setVisibility(View.VISIBLE);

            if (bean.getCate().size() == 1) {
                enterTwo.setVisibility(View.INVISIBLE);

                Glide.with(ClassicHomeActivity.this)
                        .load(bean.getCate().get(0).getCover())
                        .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                        .into(enterOne);
            } else {
                enterTwo.setVisibility(View.VISIBLE);

                Glide.with(ClassicHomeActivity.this)
                        .load(bean.getCate().get(0).getCover())
                        .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                        .into(enterOne);

                Glide.with(ClassicHomeActivity.this)
                        .load(bean.getCate().get(1).getCover())
                        .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                        .into(enterTwo);
            }
        } else {
            enterLayout.setVisibility(View.GONE);
        }

        if (bean.getAdvs() != null && bean.getAdvs().size() > 0) {
            advBanner.setVisibility(View.VISIBLE);
            advBanner.setData(bean.getAdvs().get(0).getAdvertise(), null);

            advBanner.loadImage(new XBanner.XBannerAdapter() {
                @Override
                public void loadBanner(XBanner banner, Object model, View view, int position) {
                    Glide.with(ClassicHomeActivity.this)
                            .load(((AdvertiseBean) model).getImageUrl())
                            .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                            .into((ImageView) view);
                }
            });

        } else {
            advBanner.setVisibility(View.GONE);
        }

        if (bean.getLive() != null && bean.getLive().size() > 0) {
            liveLayout.setVisibility(View.VISIBLE);
            TeleTextBean textBean = bean.getLive().get(0);
            Glide.with(this)
                    .load(textBean.getCoverPic())
                    .apply(new RequestOptions().error(R.drawable.cover_video_default).placeholder(R.drawable.cover_video_default))
                    .into(liveCover);

            liveTitle.setText(textBean.getTitle());

            if (textBean.getStatus().equals("2")) {
                liveTag.setVisibility(View.VISIBLE);
            } else {
                liveTag.setVisibility(View.GONE);
            }

        } else {
            liveLayout.setVisibility(View.GONE);
        }

        if (bean.getCatalog() != null && bean.getCatalog().size() > 0) {
            pagerLayout.setVisibility(View.VISIBLE);

            List<String> nameList = new ArrayList<>();
            List<Fragment> fragments = new ArrayList<>();

            for (int i = 0; i < bean.getCatalog().size(); i++) {
                nameList.add(bean.getCatalog().get(i).getName());
                fragments.add(ClassicHomeNewsFragment.newInstance(bean.getCatalog().get(i).getContentId() + ""));
            }

            viewPager.setAdapter(new Adapter(getSupportFragmentManager(), fragments, nameList));
            tabLayout.setViewPager(viewPager);
            tabLayout.getTitleView(0).getPaint().setFakeBoldText(true);
        } else {
            pagerLayout.setVisibility(View.GONE);
        }

    }

    @Override
    public void setError(String msg) {
        loadMask.setReloadButtonText("点击重试~");
        refresh.finishRefresh();

        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setErrorText(msg);
        if (msg.contains("网络")) {
            loadMask.setErrorImage(R.drawable.error_network);
        } else if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
        }
    }


    @OnClick({R2.id.enter_one, R2.id.enter_two, R2.id.live_more, R2.id.more, R2.id.live_cover, R2.id.back_btn})
    public void onClick(View view) {
        int viewId = view.getId();
        Bundle bundle = new Bundle();
        if (viewId == R.id.enter_one) {
            skip(mBean.getCate().get(0), false);
        } else if (viewId == R.id.enter_two) {
            skip(mBean.getCate().get(1), false);
        } else if (viewId == R.id.live_more) {
            bundle.putString("type", "3");
            RouterManager.router(ARouterPathConstant.TELETEXT_LIST, bundle);
        } else if (viewId == R.id.more) {
            int index = tabLayout.getCurrentTab();
            bundle.putString("id", mBean.getCatalog().get(index).getContentId() + "");
            bundle.putString("title", mBean.getCatalog().get(index).getName());
            RouterManager.router(ARouterPathConstant.CLASSIC_NEWS_LIST, bundle);
        } else if (viewId == R.id.live_cover) {
            bundle.putString("id", mBean.getLive().get(0).getId() + "");
            if (mBean.getLive().get(0).getType().equals("1")) {
                RouterManager.router(ARouterPathConstant.TELE_VIDEO_ACTIVITY, bundle);
            } else {
                RouterManager.router(ARouterPathConstant.TELE_TEXT_ACTIVITY, bundle);
            }

        } else if (viewId == R.id.back_btn) {
            finish();
        }
    }

    private void skip(ClassicCateBean bean, boolean isTop) {
        Bundle bundle = new Bundle();
        switch (bean.getType()) {
            case "VIDEO":
//                if (isTop) {
//                    Router.build("short_video_main")
//                            .with("title", bean.getName())
//                            .with("id", bean.getTypeDes())
//                            .go(ClassicHomeActivity.this);
//                } else {
//                    Router.build("short_video_main")
//                            .with("title", bean.getName())
//                            .with("id", bean.getContentId() + "")
//                            .go(ClassicHomeActivity.this);
//                }
                break;
            case "READING":
                if (isTop) {
                    bundle.putString("title", StringUtils.isEmpty(bean.getName()) ? "" : bean.getName());
                    bundle.putString("actId", bean.getTypeDes());
                    RouterManager.router(ARouterPathConstant.SHORT_VIDEO_THEME_NEW, bundle);
                } else {
                    bundle.putString("title", StringUtils.isEmpty(bean.getName()) ? "" : bean.getName());
                    bundle.putString("actId", bean.getContentId() + "");
                    RouterManager.router(ARouterPathConstant.SHORT_VIDEO_THEME_NEW, bundle);
                }
                break;
            case "PROGRAM":
                if (isTop) {
                    bundle.putString("title", bean.getName());
                    bundle.putString("id", bean.getTypeDes());
                    RouterManager.router(ARouterPathConstant.CLASSIC_DETAIL, bundle);
                } else {
                    bundle.putString("title", bean.getName());
                    bundle.putString("cateId", bean.getId() + "");
                    RouterManager.router(ARouterPathConstant.CLASSIC_LIST, bundle);
                }
                break;
            case "CMS_CATALOG":
                if (isTop) {
                    bundle.putString("title", bean.getName());
                    bundle.putString("id", bean.getTypeDes());
                    RouterManager.router(ARouterPathConstant.NEWS_LIST, bundle);
                } else {
                    bundle.putString("title", bean.getName());
                    bundle.putString("id", bean.getContentId() + "");
                    RouterManager.router(ARouterPathConstant.NEWS_LIST, bundle);
                }
                break;
            case "URL":
                if (isTop) {
                    bundle.putString("title", bean.getName());
                    bundle.putString("url", bean.getTypeDes());
                    bundle.putBoolean("hasShare", false);
                    RouterManager.router(ARouterPathConstant.ADV, bundle);
                }
                break;
        }
    }

    @Override
    public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {
        //Y轴偏移量
        float scrollY = who.getScrollY();

        //变化率
        float headerBarOffsetY = headerHeight - minHeaderHeight;//Toolbar与header高度的差值
        float offset = 1 - Math.max((headerBarOffsetY - scrollY) / headerBarOffsetY, 0f);
        //Toolbar背景色透明度
        toolbarLayout.setAlpha(offset);
    }


    static class Adapter extends FragmentPagerAdapter {
        private List<Fragment> fragmentList;
        private List<String> names;

        Adapter(FragmentManager fm, List<Fragment> fragmentList, List<String> names) {
            super(fm);
            this.fragmentList = fragmentList;
            this.names = names;
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return names.get(position);
        }
    }

    private void advSkip(AdvertiseBean advertiseBean) {
        if (StringUtils.isEmpty(advertiseBean.getLink())) {
            switch (advertiseBean.getLinkType()) {
                case "1": {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", advertiseBean.getLinkId());
                    RouterManager.router(ARouterPathConstant.TELE_VIDEO_ACTIVITY, bundle);
                }
                break;
                case "2": {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", advertiseBean.getLinkId());
                    RouterManager.router(ARouterPathConstant.SCOOP_DETAIL_ACTIVIT, bundle);
                }
                break;
                case "3":
                    switch (advertiseBean.getContentType()) {
                        case "1": {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", advertiseBean.getLinkId());
                            RouterManager.router(ARouterPathConstant.NORMAL_NEWS_ACTIVITY, bundle);
                        }
                        break;
                        case "2": {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", advertiseBean.getLinkId());
                            bundle.putString("section", advertiseBean.getCatalogID());
                            RouterManager.router(ARouterPathConstant.PICTURE_NEWS_ACTIVITY, bundle);
                        }
                        break;
                        case "3":
                            break;
                        case "4":
                            break;
                        case "5": {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", advertiseBean.getLinkId());
                            RouterManager.router(ARouterPathConstant.VIDEO_NEWS_ACTIVITY, bundle);
                        }
                        break;
                        case "8": {
                        }
                        break;
                        case "101": {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", advertiseBean.getLinkId());
                            RouterManager.router(ARouterPathConstant.NEWS_CATCH, bundle);
                        }
                        break;
                        default:
                            break;
                    }
                    break;
                case "4": {
                    Bundle bundle = new Bundle();
                    bundle.putString("actId", advertiseBean.getLinkId());
                    RouterManager.router(ARouterPathConstant.ACT_DETAILS, bundle);
                    ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.ACTIVITY_DETAIL);
                }
                break;
                case "5": {
                    Bundle bundle = new Bundle();
                    String userName = CommonUtils.getInstance().getUserName();
                    bundle.putString("userName", userName);
                    bundle.putInt("id", StringUtils.isNotEmpty(advertiseBean.getLinkId()) ? Integer.parseInt(advertiseBean.getLinkId()) : 0);
                    RouterManager.routerLoginInterceptor(this, bundle, ARouterPathConstant.NINE_LUCK_DRAW);
                    ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.LOTTERY);
                }
                break;
                default:

                    break;

            }
        } else {
            Bundle bundle = new Bundle();
            bundle.putString("title", advertiseBean.getTitle());
            bundle.putString("id", advertiseBean.getId() + "");
            bundle.putString("url", advertiseBean.getLink());
            if (advertiseBean.getIsShare() != null && "0".equals(advertiseBean.getIsShare())) {
                bundle.putBoolean("hasShare", false);
            }
            RouterManager.router(ARouterPathConstant.ADV, bundle);
        }
    }
}
